<template>
	<view class="content">

		<web-view ref="webview" v-if="IsShow" fullscreen="false" @message="message" class="uni-flex-item"
			:src="OrderUrl">
			<!-- class="uni-flex-item" src="/static/html/IQCInspectionOrder.html"> -->
		</web-view>
	</view>
</template>

<script>
	const open = uni.requireNativePlugin("Html5App-openFile");
	export default {
		components: {

		},
		data() {
			return {
				IsShow: true,
				currentWebview: {},
				OrderID: null,
				OrderUrl: null, // web-view地址
				ChoiceData: {}, // 选中的协议
				NvoicesIndex: null, // 选中的第几个检验项
			}
		},
		onShow() { // 每次页面显示时
			// 千万不能给旋转屏幕添加加定时器
			plus.screen.lockOrientation('landscape-primary');

			// 当页面显示的时候，如果缓存中有下载文件的地址，则删掉该文件
			// uni.removeStorageSync('NeedRemove')
			if (uni.getStorageSync('NeedRemove')) {

				uni.removeSavedFile({
					filePath: uni.getStorageSync('NeedRemove'),
					complete: function(res) {
						// console.log(res);
						uni.removeStorageSync('NeedRemove')
					}
				});
			}


		},
		onHide() {
			// console.log(1)
		},
		onLoad() {
			var that = this;

			// let NewUrlData = this.$store.state.QmsModule.NvoicesList;
			let NewUrlData = this.$store.state.ModuleInfo_All[0]['Node'];

			console.log(this.$store.state.ModuleInfo_All)


			if (!that.$utils.isEmpty(uni.getStorageSync('OrderID'))) {
				that.OrderID = uni.getStorageSync('OrderID');

				let data = NewUrlData;

				let FindData = data.find(item => item.APPFunID == that.OrderID);

				if (that.$utils.isEmpty(FindData)) { // 如果找不到
					return
				} else {
					// that.NvoicesIndex = FindData['id'];
					that.OrderUrl = FindData['AP_Link'];
				}

				// 处理按钮权限
				let menuData = NewUrlData.filter(item => {
					return item.APPFunID == that.OrderID
				})


				setTimeout(function() {
					try {
						that.currentWebview = that.$scope.$getAppWebview().children()[0];
						// if (FindData['id'] != 5) {
						var isConnected = true;
						if (that.$store.state.QmsModule.deviceId) {
							isConnected = true;
						} else {
							isConnected = false;
						}

						that.SetEvalJsFun('GetDeviceStatus', isConnected);

						// }

						// 打开的单据, 首页直接点击单据，快捷进入
						if (uni.getStorageSync('GetDocumentInfo')) {
							// 疑惑点：拿到的时字符串格式，传入之后，可以直接 点出来；关键是转对象 会报错 Uncaught SyntaxError: Unexpected identifier
							let GetDocumentInfo = uni.getStorageSync('GetDocumentInfo')

							that.SetEvalJsFun('GetDocumentInfo', GetDocumentInfo);

						}

						// 获取用户ID
						if (Object.keys(that.$store.getters['QmsModule/UserInfo']).length) {
							let UserInfo = that.$store.getters['QmsModule/UserInfo'];
							that.SetEvalJsFun('GetUserInfo', JSON.stringify(UserInfo));
						}

						// 获取当前账套IP地址与协议地址
						if (that.Request.serverIP()) {
							let TheApi = {
								serverIP: uni.getStorageSync('serverIP'),
								IPAgreement: that.Request.IPAgreement()
							}
							that.SetEvalJsFun('SetServiceIP', JSON.stringify(TheApi));
						}


						// 处理按钮权限数据
						// console.log(menuData[0]['IconApprove'])
						// 如果有按钮权限
						if (menuData[0]['IconApprove'].length) {
							let buttonPermission = menuData[0]['IconApprove'];
							that.SetEvalJsFun('GetBtnPermission', JSON.stringify(buttonPermission));
						}

						// 获取选中协议是否有值,这个是体现，选中的协议是什么
						let HasData = that.$store.getters['QmsModule/HistoryDevice'].length;
						if (HasData > 0) {
							let ChoiceData = that.$store.getters['QmsModule/HistoryDevice'][that.$store
								.getters['QmsModule/CheckHisValue']
							];
							that.ChoiceData = that.$store.getters['QmsModule/HistoryDevice'][that.$store.getters[
								'QmsModule/CheckHisValue']];
							// 获取选中协议的设备类型
							let DeviceInfo = {
								Communication: ChoiceData.Communication,
								DeviceName: ChoiceData.DeviceName,
							}
							that.SetEvalJsFun('GetDeviceName', JSON.stringify(DeviceInfo));

						}

					} catch (e) {
						//TODO handle the exception
						// console.log(e)
					}



				}, 500);
			}


		},
		onReady() {
			// #ifdef APP-PLUS
			var currentWebview = this.$scope.$getAppWebview() //获取当前页面的webview对象
			setTimeout(function() {
				let wv = currentWebview.children()[0]
				wv.setStyle({
					scalable: true
				})
			}, 1000); //如果是页面初始化调用时，需要延时一下
			// #endif
		},
		beforeDestroy() {
			// plus.screen.lockOrientation('portrait-primary');
			this.OrderUrl = null;
			this.currentWebview = {};
			this.ChoiceData = {};
			this.NvoicesIndex = null;

			uni.$off('Insepection_Choice')
		},
		onBackPress(options) { // 监听页面返回
			// console.log(options)
			if (options.from == 'backbutton') {
				return true;
			} else {
				// plus.screen.lockOrientation('portrait-primary');
				return false;
			}
		},
		mounted() {
			var that = this;

			// that.DownloadTbs(); // 安装Tbs
			// uni.hideKeyboard()


			// 设备连接状态变更触发，传入的值 是 Boolean 型
			uni.$on("changeDeivceStatus", function(connected) {
				try {
					// let currentWebview = that.$scope.$getAppWebview().children()[0];
					// currentWebview.evalJS(`vm.GetDeviceStatus(${connected})`)
					that.SetEvalJsFun('GetDeviceStatus', connected);
				} catch (e) {
					//TODO handle the exception
				}
			});

			// 监听连接的设备输出的值
			uni.$on('BluetoothData', function(data) {
				// console.log(data.Nums)
				var obj = {
					Model: that.ChoiceData.DeviceName // 设备类型（如：游标卡尺、千分尺）
				}

				that.SetEvalJsFun('setRange', data.Nums);
				// that.evalJs(data.Nums, obj)
			})


			// 监听下拉筛选选中的返回
			uni.$on('Insepection_Choice', function(data) {
				console.log(data)
				that.SetEvalJsFun('GetBaseCreenBack', JSON.stringify(data));

			})

		},
		methods: {
			evalJs(data, Model) {
				var that = this;
				try {
					let currentWebview = that.$scope.$getAppWebview().children()[0];

					currentWebview.evalJS(`vm.setRange('${data}')`)
				} catch (e) {
					//TODO handle the exception
				}
			},
			/** SetEvalJsFun 调用html内页面方法
			 * @param {String} FunName 调用html页面内的方法名
			 * @param {*} data 传入的参数
			 */
			SetEvalJsFun(FunName, data) {
				var that = this;
				try {
					let currentWebview = that.$scope.$getAppWebview().children()[0];

					currentWebview.evalJS(`vm.${FunName}('${data}')`)
				} catch (e) {
					//TODO handle the exception
				}
			},
			message(event) { // 接收从内部发出的信息
				var that = this;
				console.log('接收到消息', event.detail.data);

				if (event.detail.data[0]['action'] == 'ToScan') { // 扫码

					uni.scanCode({
						success: function(res) {
							// console.log('条码类型：' + res.scanType);
							// console.log('条码内容：' + res.result);

							that.currentWebview.evalJS(`vm.GetToScanInfo(${JSON.stringify(res)})`);
						}
					});
				} else if (event.detail.data[0]['action'] == 'showPopup') { // 如果是打开作业指导书
					let data = event.detail.data[0]['param'];

					that.openDocument(data);
				} else if (event.detail.data[0]['action'] == 'GoBack') { // 返回

					that.GoBack()

				} else if (event.detail.data[0]['action'] == 'ToReviewPageInfo') { // 不合格评审

					let data = event.detail.data[0]['param'];


					uni.navigateTo({
						url: '/qms/ChoiceIAddnvoices/ReviewPageInfo?id=' + data.BadReviewID
					})

				} else if (event.detail.data[0]['action'] == 'baseScreen') { // 筛选下拉

					let data = event.detail.data[0]['param'];

					that.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: data
					});

					that.$nextTick(() => {

						uni.navigateTo({
							url: '/commonPage/Tool/baseScreen'
						})
					})
				}
				//  else if (event.detail.data[0]['action'] == 'Request') { // 内部传出的请求
				// 	let data = event.detail.data[0]['param'];
				// 	that.Request.request(data.cmd, data.data, (ret) => {
				// 		console.log(ret)

				// 		if (ret.status == 200) {
				// 			that.SetEvalJsFun(`${data.cmd}_Back`, JSON.stringify(ret.data.ds))
				// 		}

				// 	})
				// }


			},
			DownloadTbs() { // 安装内核tbs
				let HasTbs = open.isLoadTbs(); // 判断是否安装内核

				if (!HasTbs) {
					// 安装文件浏览内核文件,安卓端需要
					let filepath = plus.io.convertLocalFileSystemURL("static/arm64-v8a.tbs");
					open.installLocalTbs({
						tbsFilePath: filepath,
						isdelete: false //安装好是否要删除该文件
					}, function(e) {
						console.log(JSON.stringify(e))
					});
				}
			},
			openDocument(data) { // 打开浏览
				var that = this;

				let ServerIP = that.Request.serverIP();
				data.url = that.Request.IPAgreement() + ServerIP + data.url;
				uni.downloadFile({
					url: data.url,
					success: function(res) {
						var filePath = plus.io.convertLocalFileSystemURL(res.tempFilePath);
						console.log(JSON.stringify(filePath))
						// 记录一下地址，等界面打开的时候就删除掉
						uni.setStorageSync('NeedRemove', filePath)
						open.openFile({
							filename: filePath,
							title: data.title,
							isShowBackIcon: true
						}, ret => {
							console.log(JSON.stringify(ret))
						});
					}
				})
			},
			GoBack() {
				plus.screen.lockOrientation('portrait-primary');
				this.IsShow = false;
				setTimeout(() => {
					uni.navigateBack()
				}, 300)
			},
		}
	}
</script>

<style lang="scss">
	* {
		background-color: transparent;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		/* 给顶部盒子安全高度 */
		padding-top: var(--status-bar-height);

		.popup-container {
			z-index: 1001;
			/* 设置一个较高的z-index值 */
		}
	}
</style>